package com.yx.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Classname FeignWebConfig
 * @Date 2021/07/23 19:55
 * @Author by yx
 * @Description : feign转发携带请求头信息
 */
@Configuration
public class FeignWebConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                // 把旧得请求头信息,赋值给新的请求头,将cookie传递出去
                while (headerNames.hasMoreElements()){
                    String key = headerNames.nextElement();
                    String value = request.getHeader(key);
                    template.header(key, value);
                }
            }
        };
    }
}
